/**
 * Created by liu on 16-3-1.
 */
$(function () {
    get_cart_goods();
    add_to_original_price();
});

function less(name) {
    get_cart_goods().forEach(function (good) {
        if (name == good.name) {
            $("#" + name + "_count").text(good.count -= 1);
            less_and_plus(good);
            delete_goods_info();
        }
        jump_page();
    })
}

function cart_goods_count() {
    var num = 0;
    get_cart_goods().forEach(function (good) {
        num += good.count
    });
    $('#total_goods_number').text(num);
}

function less_and_plus(good) {
    good.free_count = Math.floor(good.count / free_goods_info()[good.name]) || 0;
    save_good_count(good);
    cart_goods_count();
    price_info();
}

function save_good_count(good) {
    var url = '/cart/save_good_count';
    var success = function (data) {
    };
    var error = function () {
        alert('no')
    };
    ajax_post(url, good, success, error)
}

function present_price() {
    var num = 0;
    get_cart_goods().forEach(function (goods) {
        num += (goods.count - goods.free_count) * goods.price;
    });
    return num
}

function price_info() {
    get_cart_goods().forEach(function (good) {
        $('#' + good.name + 'price').text(((good.count - good.free_count) * good.price).toFixed(1));
        $('#' + good.name + 'list').text(good.count * good.price);
        $('#count').text((present_price()).toFixed(2));
    })
}

function plus(name_secend) {
    get_cart_goods().forEach(function (good) {
        if (name_secend == good.name) {
            if (get_goods_inventory()[good.name] - good.count == 0)return alert('已没有库存');
            $("#" + name_secend + "_count").text(good.count += 1);
            less_and_plus(good);
        }
    });
}

function delete_goods_info() {
    get_cart_goods().forEach(function (value, index) {
        delete_good(value.count, get_cart_goods(), index, value)
    })
}

function delete_good(key_num, goods, index, value) {
    if (key_num == 0) { //0 == number    //var number = 0;
        goods.splice(index, 1);
        //save_good(goods);
        $('#' + value.name + 'tr').hide();
    }
}

function jump_page() {
    if (document.getElementById('total_goods_number').innerHTML == 0) {
        window.location.href = '/list/product_list'
    }
}